﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using CorreoSocialWeb.Models;
using CorreoSocialWeb.Views;

using Subgurim.Controles;
using Subgurim.Controles.GoogleChartIconMaker;

namespace CorreoSocialWeb.Controls
{
    public partial class EditarRutaUserControl : System.Web.UI.UserControl
    {
        private FormViewRutaControlHelper ViewControls;
        private CoordenadasDeSesionHelper CoordenadasDeSesion;

        private Models.Ruta item;

        public Models.Ruta Item
        {
            get
            {
                return item;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.PreRenderComplete += Page_PreRenderComplete;

            this.ViewControls = new FormViewRutaControlHelper(this);
            this.CoordenadasDeSesion = new CoordenadasDeSesionHelper(this.Page);

            var titulo = string.Format("{0} Ruta", this.AgregandoItem ? "Nueva" : "Editar");
            this.Page.Title = 
            this.LabelTitulo.Text = titulo;

            if (this.IsPostBack)
                return;

            this.LabelError.Text = string.Empty;
            this.PanelVolverError.Visible = false;
            this.PanelForm.Visible = true;

            Mapa.enableDragging = false;
            Mapa.Language = "es";
            Mapa.BackColor = System.Drawing.Color.White;

            // las coordenadas las cargo después, al obtener el item para insertar o editar
            this.CoordenadasDeSesion.Borrar();

            this.CargarItem();
        }

        private void GetItem()
        {
            item = new Models.Ruta();

            if (!this.AgregandoItem)
            {
                var usuarioId = new Views.UsuarioDePaginaHelper().GetUsuarioId(this.Context);

                item = Models.Ruta.GetParaEditar(usuarioId, this.ItemId.Value);
            }
        }

        void Page_PreRenderComplete(object sender, EventArgs e)
        {
            if (this.IsPostBack)
                return;

            if (!this.PanelForm.Visible)
                return;

            this.DataBind();
        }

        protected void Control_OnPreRender(object sender, EventArgs e)
        {
            if (this.IsPostBack)
                return;

            if (!this.PanelForm.Visible)
                return;

            this.DataBind();
        }

        public IQueryable DropDownListTamanoDePaquete_SelectMethod()
        {
            return TamanoDePaqueteComboItemsHelper.Get().AsQueryable();
        }
        
        protected void LinkButtonCancelar_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Rutas/MisRutas", false);
        }

        protected void ButtonOrigen_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Rutas/ActualizarPosicion", false);
        }

        private int? ItemId
        {
            get
            {
                if (Request.QueryString["Id"] != null)
                    return int.Parse(Request.QueryString["Id"]);

                return null;
            }
        }

        private bool AgregandoItem
        {
            get
            {
                return !this.ItemId.HasValue;
            }
        }

        public void CargarItem()
        {
            LimpiarMapa();

            try
            {
                GetItem();

                if (this.Item == null)
                    throw new Exception("Ruta no encontrada.");

                CargarMarkers(this.Item);
            }
            catch
            {
                this.LabelError.Text = "Error al obtener ruta.";
                this.PanelForm.Visible = false;
                this.PanelVolverError.Visible = true;
            }
        }

        private void CargarMarkers()
        {
            CargadorDeMarkers.Cargar(this.CoordenadasDeSesion, this.Mapa);
        }

        private void CargarMarkers(Models.Ruta item)
        {
            this.CoordenadasDeSesion.Cargar(item);

            this.CargarMarkers();
        }

        protected string Mapa_Click(object s, GAjaxServerEventArgs e)
        {
            var coordenadas = new CoordenadasDeSesionHelper(this.Page);

            return CargadorDeMarkers.MapaClick(this.Mapa, coordenadas, e);
        }

        private void LimpiarMapa()
        {
            Views.MapaHelper.Limpiar(this.Mapa);

            this.CoordenadasDeSesion.Borrar();
        }

        private void LimpiarLabels()
        {
            this.LabelError.Text =

            this.LabelErrorOrigen.Text =
            this.LabelErrorDestino.Text =

            this.LabelErrorTamanoDePaquete.Text =

            this.LabelErrorHorarioDeSalida.Text =
            this.LabelErrorHorarioDeLlegada.Text =

            this.LabelErrorDisponibilidad.Text =

            this.LabelErrorCoordenadaOrigen.Text =
            this.LabelErrorCoordenadaDestino.Text = string.Empty;
        }

        public void GuardarItem()
        {
            ErroresHelper errores = new ErroresHelper();
            var db = new CorreoSocialDbContext();
            var item = new CorreoSocialWeb.Models.Ruta();

            try
            {
                LimpiarLabels();

                CargarMarkers();

                var usuarioId = new UsuarioDePaginaHelper().GetUsuarioId(this.Context);

                if (!this.AgregandoItem)
                    item = Models.Ruta.GetParaEditar(db, usuarioId, this.ItemId.Value);

                if (!this.ViewControls.Validar(errores))
                {
                    this.LabelError.Text = "Hubo errores de validación. Revisá los valores ingresados y volvé a intentarlo.";
                    return;
                }

                item.Origen = this.ViewControls.Origen.Trim();
                item.Destino = this.ViewControls.Destino;
                
                item.HoraDeSalida = this.ViewControls.HoraDeSalida.Value;
                item.MinutosDeSalida = this.ViewControls.MinutosDeSalida.Value;

                item.HoraDeLlegada = this.ViewControls.HoraDeLlegada.Value;
                item.MinutosDeLlegada = this.ViewControls.MinutosDeLlegada.Value;

                item.TamanoDePaqueteId = this.ViewControls.TamanoDePaqueteId;

                item.Lunes = this.ViewControls.Lunes;
                item.Martes = this.ViewControls.Martes;
                item.Miércoles = this.ViewControls.Miércoles;
                item.Jueves = this.ViewControls.Jueves;
                item.Viernes = this.ViewControls.Viernes;
                item.Sábado = this.ViewControls.Sábado;
                item.Domingo = this.ViewControls.Domingo;

                
                item.CoordenadasOrigen = this.CoordenadasDeSesion.Origen;
                item.CoordenadasDestino = this.CoordenadasDeSesion.Destino;
                
                item.Notas = this.ViewControls.Notas;

                item.Activa = this.ViewControls.Activa;

                if (item.EsNueva)
                {
                    // busco asignarle el usuario al envío, si es que es nuevo
                    item.UsuarioId = usuarioId;
                    db.Rutas.Add(item);
                }

                db.SaveChanges();
            }
            catch
            {
                this.LabelError.Text = "Hubo un error al guardar la Ruta. Por favor, intentá nuevamente más tarde.";
                return;
            }

            Response.Redirect("~/Rutas/MisRutas", false);
        }

        protected void LinkButtonLimpiarMapa_Click(object sender, EventArgs e)
        {
            this.LimpiarMapa();
        }

        protected void LinkButtonGuardar_Click(object sender, EventArgs e)
        {
            this.GuardarItem();
        }

        #region Controles
        /// <summary>
        /// LabelTitulo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelTitulo;
        
        /// <summary>
        /// LabelError control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelError;
        
        /// <summary>
        /// PanelForm control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Panel PanelForm;
        
        /// <summary>
        /// LabelErrorCoordenadaOrigen control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorCoordenadaOrigen;
        
        /// <summary>
        /// LabelErrorCoordenadaDestino control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorCoordenadaDestino;
        
        /// <summary>
        /// PanelMap control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Panel PanelMap;
        
        /// <summary>
        /// Mapa control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::Subgurim.Controles.GMap Mapa;
        
        /// <summary>
        /// LinkButtonLimpiarMapa control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.LinkButton LinkButtonLimpiarMapa;
        
        /// <summary>
        /// LabelOrigen control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelOrigen;
        
        /// <summary>
        /// LabelErrorOrigen control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorOrigen;
        
        /// <summary>
        /// TextboxOrigen control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.TextBox TextboxOrigen;
        
        /// <summary>
        /// LabelTamanoDePaquete control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelTamanoDePaquete;
        
        /// <summary>
        /// LabelErrorTamanoDePaquete control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorTamanoDePaquete;
        
        /// <summary>
        /// DropDownListTamanoDePaquete control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.DropDownList DropDownListTamanoDePaquete;
        
        /// <summary>
        /// LabelDestino control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelDestino;
        
        /// <summary>
        /// LabelErrorDestino control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorDestino;
        
        /// <summary>
        /// TextboxDestino control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.TextBox TextboxDestino;
        
        /// <summary>
        /// LabelDisponibilidad control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelDisponibilidad;
        
        /// <summary>
        /// LabelErrorDisponibilidad control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorDisponibilidad;
        
        /// <summary>
        /// CheckBoxLunes control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxLunes;
        
        /// <summary>
        /// CheckBoxSabado control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxSabado;
        
        /// <summary>
        /// CheckBoxMartes control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxMartes;
        
        /// <summary>
        /// CheckBoxDomingo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxDomingo;
        
        /// <summary>
        /// CheckBoxMiercoles control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxMiercoles;
        
        /// <summary>
        /// CheckBoxJueves control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxJueves;
        
        /// <summary>
        /// CheckBoxViernes control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxViernes;
        
        /// <summary>
        /// LabelHorarioDeSalida control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelHorarioDeSalida;
        
        /// <summary>
        /// LabelErrorHorarioDeSalida control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorHorarioDeSalida;
        
        /// <summary>
        /// TextboxHoraDeSalida control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.TextBox TextboxHoraDeSalida;
        
        /// <summary>
        /// TextboxMinutosDeSalida control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.TextBox TextboxMinutosDeSalida;
        
        /// <summary>
        /// LabelNotas control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelNotas;
        
        /// <summary>
        /// TextBoxNotas control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.TextBox TextBoxNotas;
        
        /// <summary>
        /// LabelHorarioDeLlegada control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelHorarioDeLlegada;
        
        /// <summary>
        /// LabelErrorHorarioDeLlegada control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelErrorHorarioDeLlegada;
        
        /// <summary>
        /// TextboxHoraDeLlegada control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.TextBox TextboxHoraDeLlegada;
        
        /// <summary>
        /// TextboxMinutosDeLlegada control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.TextBox TextboxMinutosDeLlegada;
        
        /// <summary>
        /// LabelActiva control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Label LabelActiva;
        
        /// <summary>
        /// CheckBoxActiva control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.CheckBox CheckBoxActiva;
        
        /// <summary>
        /// PanelButtons control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Panel PanelButtons;
        
        /// <summary>
        /// LinkButtonGuardar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.LinkButton LinkButtonGuardar;
        
        /// <summary>
        /// LinkButtonCancelar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.LinkButton LinkButtonCancelar;
        
        /// <summary>
        /// PanelVolverError control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.Panel PanelVolverError;
        
        /// <summary>
        /// LinkButtonVolver control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        public global::System.Web.UI.WebControls.LinkButton LinkButtonVolver;

        #endregion
    }
}